//
//  ThreadPool.m
//  helloworld
//
//  Created by didi on 11/06/2024.
//

#import "ThreadPool.h"

@interface ThreadPool ()

@property (nonatomic, strong) dispatch_queue_t queue;
@property (nonatomic, assign) BOOL isShutdown;

@end

@implementation ThreadPool

- (instancetype)initWithSize:(NSUInteger)size {
    self = [super init];
    if (self) {
        self.isShutdown = NO;
        self.queue = dispatch_queue_create("com.example.threadpool", DISPATCH_QUEUE_CONCURRENT);
        for (NSUInteger i = 0; i < size; i++) {
            dispatch_async(self.queue, ^{
                while (!self.isShutdown) {
                    @autoreleasepool {
                        // 阻塞等待任务
                        dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
                        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                            dispatch_semaphore_signal(semaphore);
                        });
                        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
                    }
                }
            });
        }
    }
    return self;
}

- (void)execute:(void (^)(void))task {
    if (self.isShutdown) {
        return;
    }
    dispatch_async(self.queue, task);
}

- (void)shutdown {
    self.isShutdown = YES;
}

@end

